package main

import (
    "fmt"
    "log"
    "time"
    clients "github.com/influxdata/influxdb/client/v2"
)

// influxdb demo

func connInflux() clients.Client {
    cli, err := clients.NewHTTPClient(clients.HTTPConfig{
        Addr:     "http://127.0.0.1:8086",
        Username: "root",
        Password: "123qwe",
    })
    if err != nil {
        log.Fatal(err)
    }
    return cli
}

// query
func queryDB(cli clients.Client, cmd string) (res []clients.Result, err error) {
    q := clients.Query{
        Command:  cmd,
        Database: "prometheus",
    }
    if response, err := cli.Query(q); err == nil {
        if response.Error() != nil {
            return res, response.Error()
        }
        res = response.Results
    } else {
        return res, err
    }
    return res, nil
}

// insert
func writesPoints(cli clients.Client) {
    bp, err := clients.NewBatchPoints(clients.BatchPointsConfig{
        Database:  "prometheus",
        Precision: "s",
    })
    if err != nil {
        log.Fatal(err)
    }
    t, _ := time.ParseInLocation("20060102", "20220425", time.Local)
    tags := map[string]string{"mount": "/home", "ip":""}
    fields := map[string]interface{}{
        "value":  3,
    }

    pt, err := clients.NewPoint("df", tags, fields, t)
    if err != nil {
        log.Fatal(err)
    }
    bp.AddPoint(pt)

    tags2 := map[string]string{"mount": "/home", "instance":"2.2.2.2"}
    fields2 := map[string]interface{}{
        "value":  7,
    }
    pt2, _ := clients.NewPoint("df", tags2, fields2, t)
    bp.AddPoint(pt2)

    err = cli.Write(bp)
    if err != nil {
        log.Fatal(err)
    }


    log.Println("insert success")
}

func main() {
    conn := connInflux()
    fmt.Println(conn)

    // insert
    writesPoints(conn)

    //qs := fmt.Sprintf("SELECT * FROM %s LIMIT %d", "cpu_usage", 10)
    qs := fmt.Sprintf("SHOW  series from df")
    res, err := queryDB(conn, qs)
    if err != nil {
        log.Fatal(err)
    }
    rows := res[0].Series
    for _ , row := range rows{
        fmt.Println(1111, row)
    }


    qs = fmt.Sprintf("SELECT * FROM %s group by * LIMIT %d ", "df", 10)
    res, err = queryDB(conn, qs)
    if err != nil {
        log.Fatal(err)
    }
    rows = res[0].Series
    for _ , row := range rows{
        fmt.Println(22222, row)
    }
}
